package com.kis.core.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wongloong on 16-5-17.
 */
public class StringTools {
    public static String getHost(String url) {
        String host = "";
        if (url.indexOf("http://") > -1) {
            url = url.replaceAll("http://", "");
        }
        if (null != url && url.indexOf(":") > 0) {
            String[] sArray = url.split(":");
            host = sArray[1];
        }
        return host;
    }

    public static Integer getPort(String url) {
        Integer defaultPort = 80;
        if (null != url && url.indexOf(":") > 0) {
            try {
                String[] sArray = url.split(":");
                defaultPort = Integer.parseInt(sArray[2]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return defaultPort;
    }

    public static String getKey(String s) {
        String key = "";
        Pattern keyPattern = Pattern.compile("(?<=\\d{4,5})\\/+\\w+\\/*\\w+");
        Matcher matcher = keyPattern.matcher(s);
        while (matcher.find()) {
            key = matcher.group();
        }
        key = key.replaceAll("\\/{2,}", "/");
        return key;
    }

    public static String getUrl(String s) {
        String url = "";
        Pattern urlPattern = Pattern.compile("http://[^\\s]*:\\d*");
        Matcher urlMatcher = urlPattern.matcher(s);
        while (urlMatcher.find()) {
            url = urlMatcher.group();
        }
        return url;
    }

    public static List<String> getClassPaths(Enumeration enumeration, String scanPackage) {
        List<String> list = new ArrayList<String>();
        if (scanPackage.startsWith("/")) {
            scanPackage = scanPackage.substring(1);
        }
        scanPackage = scanPackage.replaceAll("\\.","/");
        while (enumeration.hasMoreElements()) {
            JarEntry jarEntry = (JarEntry) enumeration.nextElement();
            String name = jarEntry.getName();
            if (name.indexOf(scanPackage) > -1 && name.endsWith(".class")) {
                list.add(name.replaceAll("/","\\."));
            }
        }
        return list;
    }
}
